import JsCookie from "js-cookie";

import router from "@/router";

const TokenKey = "RSB_V2";

/**
 * @description 存储 Token
 * @param {String} token Token
 * @param {String} key TokenKey
 **/
export const setToken = (token = null, key = TokenKey) => {
	JsCookie.set(key, token, { expires: 7 });
};

/**
 * @description 获取 Token
 * @param {String} key TokenKey
 * @return {String} Token
 **/
export const getToken = (key = TokenKey) => {
	return JsCookie.get(key) || "";
};

/**
 * @description 删除 Token
 * @param {Boolean} isRedirect 是否跳转登录页
 **/
export const removeToken = (isRedirect = false) => {
	localStorage.clear();
	sessionStorage.clear();
	const JwtKeys = Object.keys(JsCookie.get());
	JwtKeys.forEach(key => JsCookie.remove(key));
	if (isRedirect) router.push({ name: "Login", replace: true });
};

/**
 * @description 创建 Token
 * @param {String} username 用户名
 * @param {String} password 密码
 * @return {String} Token
 **/
export const createToken = ({ password, username }) => {
	return window.btoa(`${password}:${username}`) || "";
};
